package com.tedu.springboot2302k.controller;

import com.tedu.springboot2302k.entity.Article;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Controller
public class ArticleController {

    //静态加载一个文件夹，用来存储文章
    private  static File articleDir;
    static {
        articleDir=new File("./articles");
        if (!articleDir.exists()){
            articleDir.mkdirs();
        }
    }

    //文章处理的方法：
    @RequestMapping("/publish")
    public void writeArticle(HttpServletRequest request, HttpServletResponse response){
        System.out.println("开始处理用户写作...");
        //获取信息
        String title=request.getParameter("title");
        String name=request.getParameter("name");
        String article=request.getParameter("article");
        System.out.println(title+name+article);
        //判断信息是否正确
        //如果错误，返回错误页面
        if (title==null||title.isEmpty()||
                name==null||name.isEmpty()||
                article==null||article.isEmpty()
        ) {
            try {
                response.sendRedirect("/Published_failed.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return;
        }

        //如果正确:
        //建立对象流
        File file =new File(articleDir,title+".obj");
        if(file.exists()){
            try {
                response.sendRedirect("/Published_failed.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        try {
            file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Article article1=new Article(title,name,article);
        //对内容进行序列化，对内容进行存储
        try(FileOutputStream fos=new FileOutputStream(file);
            ObjectOutputStream oos=new ObjectOutputStream(fos)) {
            oos.writeObject(article1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //返回正确页面
        try {
            response.sendRedirect("Published_successfully.html");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return;
    }


}
